<template>
  <el-time-picker
    is-range
    @change="handleChangeTime"
    v-model="defaultValue"
    range-separator="至"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    :clearable="false"
    align="right"
  >
  </el-time-picker>
</template>
<script>
const moment = require('moment')
export default {
  props: {
    timeBegin: {
      type: [String, Date],
      default: ''
    },
    timeEnd: {
      type: [String, Date],
      default: ''
    },
    isDefaultToday: {
      type: Boolean,
      default: false
    },
    timePickerItem: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      num: 1,
      defaultValue: []
    }
  },
  methods: {
    handleChangeTime(val) {
        const startTimer = moment(val[0]).format('YYYY-MM-DD HH:mm:ss')
        const endTimer = moment(val[1]).format('YYYY-MM-DD HH:mm:ss')

        let startTimerP = moment(val[0]).format('HH:mm:ss')
        let endTimerP = moment(val[1]).format('HH:mm:ss')
        this.defaultValue = [startTimer, endTimer]
        console.log(this.defaultValue);
        if(startTimerP == endTimerP) {
          this.$message.error('开始时间和结束时间不能相同')
          this.defaultValue[1] = moment(val[0]).add(1, 'hours').format('YYYY-MM-DD HH:mm:ss')
          endTimerP = moment(val[1]).add(1, 'hours').format('HH:mm:ss')
        }
        if (this.num == 1) {
          setTimeout(() => {
            this.num = 0
          }, 500);
          return
        } else {
          this.timePickerItem.forEach(item => {
          // console.log(item.beginTime,item.endTime);
          if(startTimerP == item.beginTime && endTimerP == item.endTime) {
            this.$message.error('该时间段已被占用')
            this.defaultValue[1] = moment(val[0]).add(1, 'hours').format('YYYY-MM-DD HH:mm:ss')
            endTimerP = moment(val[1]).add(1, 'hours').format('HH:mm:ss')
          }
        })
        }
        this.$emit('update:timeBegin', startTimerP)
        this.$emit('update:timeEnd', endTimerP)
    }
  },
  mounted() {
    // 传指定时间
    if (this.timeBegin && this.timeEnd) {
      this.defaultValue = [
        '2020-2-20 ' + this.timeBegin,
        '2020-2-20 ' + this.timeEnd
      ]
    } else if (this.isDefaultToday) {
      // 没传指定时间
      // const monthTime = new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 30);
      this.$set(this.defaultValue, 0, '2020-2-20 09:00:00')
      this.$set(this.defaultValue, 1, '2020-2-20 18:00:00')
      this.handleChangeTime(this.defaultValue)
    }
  }
}
</script>
